$(function(){
	
	var supplierId = $(".supplierId").val();
	var warehouseId;
	var cartGoods;
	
	$('.datepicker').datepicker({
	     format: "yyyy-mm-dd",
	     language: "zh-CN",
	     orientation: "top left",
	     autoclose:true
	});
	var dataTable = $('#returnGoods').dataTable({
		"ColumnDefs" : [ {
	        sDefaultContent : '',
	        aTargets : [ '_all' ]
		} ],
		bFilter: false,
        aaData: [],
        "bPaginate": false,
        aoColumns: [
            {mDataProp:"taosku"},
            {mDataProp:"bn"},
            {mDataProp:"goodsName"},
            {mDataProp:"taxRate"},
            {mDataProp:"avaliableNum"},
            {mDataProp:"perWeekSaleNum"},
            {mDataProp:"costPrice"},
            {mDataProp:"purchasePrice"},
            {mDataProp:"returnPrice"},
            {mDataProp:"packageSpec"},
            {mDataProp:"receiveNum"},
            {mDataProp:"defectiveNum"},
            {mDataProp:"returnNum"},
            {mDataProp:"goodsAmount"},
            {mDataProp:"goodsId"},
            {mDataProp:"goodsSpecId"}
        ],
        columnDefs:[{
        	targets:[8],
        	data:"returnPrice",
        	render: function(data, type, full) {
                return "<input type='text' class='returnPrice userEdit' value="+ data+">";
            }
        },
        {
        	targets:[12],
        	data:"returnNum",
        	render: function(data, type, full) {
                return "<input type='text' class='returnNum userEdit'  value=0>";
            }
        },
        {
        	targets:[14],
        	"bVisible": false,
        	data:"goodsId",
        },
        {
        	targets:[15],
        	"bVisible": false,
        	data:"goodsSpecId",
        }]
    } );
	$(".warehouseSelect").change(function(){
		warehouseId = $(this).val();
		console.log(warehouseId);
		if(warehouseId==-1){
			return false;
		}
		cartGoods = sessionStorage.getItem("LKT-CART-RETURN"+warehouseId);
		if(cartGoods){
			cartGoods = JSON.parse(sessionStorage.getItem("LKT-CART-RETURN"+warehouseId));
			//TODO   to get the already chosen goods
			initTable();
		}
		else{
			cartGoods = {};
		}
		RefreshTableByData("#returnGoods","getWarehouseGoods?warehouseId="+warehouseId+"&supplierId="+supplierId);
	});
	
	
	
	//change display of button
	$(".clearRelative").click(function(){
			dataTable.fnClearTable();
	});
	$(".chooseRelative").click(function(){
			if(!warehouseId){
				alert("请选择仓库");
				return false;
			}
			RefreshTable("#supplierGoods","supplierGoods?warehouseId="+warehouseId+"&supplierId="+supplierId);
	});
	//
	$("#returnGoods").on("change",".userEdit",function(){
		console.log($(this).val());
		var value = $(this).val();
		if(isNaN(value) || value<0)
		{
			alert("请输入正确数字！");
			return false;
		}
		var row = $(this).parents("tr");
		var returnPrice = row.find('.returnPrice').val();
		var returnNum = row.find('.returnNum').val();
		var aData = dataTable.fnGetData($(row)); // get datarow
		
         if (null != aData && returnNum!==0)  // null if we clicked on title row
         {
        	 aData['purchaseNum'] = value;
        	 computeTotalAmount(row);
//           function GoodsDetail(goodsId,goodsSpecId,taosku,bn,goodsName,taxRate,avaliableNum,perWeekSaleNum,costPrice,purchasePrice,packageSpec,defectiveNum,goodsAmount,returnPrice,returnNum)
             var goods = new GoodsDetail(aData['goodsId'],aData['goodsSpecId'],"","",aData['goodsName'],0,0,0,0,0,0,0,0,returnPrice,returnNum);
             cartGoods[aData['goodsId']] = goods;
         }
	});
	
	function getOrderValue(){
		var planReturntime = $(".planReturntime").val();
		var address = $("#address").val();
		var remark = $("#remark").val();
		var reason = $("#reason").val();
		var submitOrder = {};
		submitOrder.planReturntime=planReturntime;
		submitOrder.address=address;
		submitOrder.remark=remark;
		submitOrder.reason=reason;
		submitOrder.supplierId = supplierId;
		submitOrder.warehouseId = warehouseId;
		var details = [];
		for(var p in cartGoods){
			if(cartGoods.hasOwnProperty(p)){
				details.push(cartGoods[p]);
			}
		}
		submitOrder.details = details;
		submitOrder = JSON.stringify(submitOrder);
		return submitOrder;
	}
	
	$(".submitOrder").click(function(){
		var data = getOrderValue();
		$.ajax({
			url:"submitReturnOrder",
			type:'post',
			data:data,
			contentType: "application/json; charset=utf-8",
			dataType:"json",
			success:function(data){
				alert("退货成功！");
//				var href = "/po_purchase/purchaseReturnReview";
//				$(".wrapper-content").load(href);
			},
			error:function(){
				
			}
		});
	});
	
	$(window).unload(saveToSessionStorage);
	function saveToSessionStorage(){
		sessionStorage.setItem('LKT-CART-RETURN'+warehouseId,JSON.stringify(cartGoods));
	}
	function RefreshTableByData(tableId, urlData)
    {
		$.getJSON(urlData, null, function( data )
		{
			//Retrieve the new data with $.getJSON. You could use it ajax too
	        table = $(tableId).dataTable();
	        oSettings = table.fnSettings();

	        table.fnClearTable(this);

	        for (var i=0; i<data.length; i++)
	        {
	            table.oApi._fnAddData(oSettings, data[i]);
		        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
		        table.fnDraw();
	        }
	    });
      
    }
	function RefreshTable(tableId, urlData)
    {
      //Retrieve the new data with $.getJSON. You could use it ajax too
      $.getJSON(urlData, null, function( json )
      {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.data.length; i++)
        {
          table.oApi._fnAddData(oSettings, json.data[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
      });
    }
//	function GoodsDetail(goodsId,goodsSpecId,taosku,bn,goodsName,taxRate,avaliableNum,perWeekSaleNum,costPrice,purchasePrice,packageSpec,defectiveNum,goodsAmount,returnPrice,returnNum){
	function GoodsDetail(goodsId,goodsSpecId,taosku,bn,goodsName,taxRate,avaliableNum,perWeekSaleNum,costPrice,purchasePrice,packageSpec,defectiveNum,goodsAmount,returnPrice,returnNum){
		var obj = {};
		obj.goodsId = goodsId;
		obj.goodsSpecId = goodsSpecId;
		obj.taosku = taosku;
		obj.bn = bn;
		obj.goodsName = goodsName;
		obj.taxRate = taxRate;
		obj.avaliableNum = avaliableNum;
		obj.perWeekSaleNum = perWeekSaleNum;
		obj.costPrice = costPrice;
		obj.purchasePrice = purchasePrice;
		obj.packageSpec = packageSpec;
		obj.defectiveNum = defectiveNum;
		obj.goodsAmount = goodsAmount;
		obj.returnPrice = returnPrice;
		obj.returnNum = returnNum;
		return obj;
	}
	function initTable(){
		
	}
	function computeTotalAmount($row){
		var total = parseFloat($row.find('.price').val())*parseFloat($row.find('.rate').val())*parseInt($row.find('.buyAmount').val());
		$row.find('.amount').val(total);
	}
});
